<template>
	<div class="session-management">
		<h2>会话管理</h2>
		<el-table :data="sessions" style="width: 100%">
			<el-table-column prop="userId" label="用户ID" width="100"/>
			<el-table-column prop="ip" label="IP地址" width="150"/>
			<el-table-column prop="token" label="登录标识" />
			<el-table-column prop="createdAt" label="登录时间" width="180">
				<template slot-scope="scope">
					<!-- 格式化时间 1746121677846 为yyyy-MM-dd HH:mm:ss-->
					{{ new Date(scope.row.createdAt).toLocaleString() }}
				</template>
			</el-table-column>
			<el-table-column prop="expiresIn" label="有效时间(s)" width="180">
				<template slot-scope="scope">
					{{ scope.row.expiresIn | formatDate }}
				</template>
			</el-table-column>
			<el-table-column label="操作" width="120">
				<template slot-scope="scope">
					<el-button type="danger" size="small" @click="handleRevoke(scope.row)">
						注销
					</el-button>
				</template>
			</el-table-column>
		</el-table>
	</div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { sessionList, delSession } from '@/api/session'
import { logout } from '@/api/user_api'

export default {
	data () {
		return {
			sessions: []
		}
	},
	methods: {
		fetchSessions () {
			sessionList().then(res => {
				this.sessions = res.data.data
			})
		},
		handleRevoke (session) {
			try {
				this.$confirm('确定要注销该会话吗？', '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					delSession(session.token).then(res => {
						if (res.data.code == 200) {
							this.$message.success('会话已注销')
						}
					})

					// 如果注销的会话是当前会话，则刷新页面
					console.log(session.token == localStorage.getItem('token'))
					if (session.token == localStorage.getItem('token')) {
						logout().then(res => {
							if (res.data.code == 200) {
								localStorage.clear()
								this.$router.push('/index/1')
							}
						})
					}
					// 刷新页面
					this.fetchSessions()
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					});
				})
			} catch (error) {
				console.log(error)
				this.$message.error('注销会话失败')
			}
		}
	},
	mounted () {
		this.fetchSessions()
	}
}
</script>

<style scoped>
.session-management {
	padding: 20px;
}
</style>